<template>
  <div class="bill-container">
    <div class="bill-header">
      <h2>账单查询</h2>
      <div class="bill-summary">
        <div class="summary-card">
          <el-icon><Money /></el-icon>
          <div class="summary-content">
            <span class="label">总消费</span>
            <span class="value">¥{{ totalAmount }}</span>
          </div>
        </div>
        <div class="summary-card">
          <el-icon><Timer /></el-icon>
          <div class="summary-content">
            <span class="label">总充电时长</span>
            <span class="value">{{ totalDuration }}</span>
          </div>
        </div>
        <div class="summary-card">
          <el-icon><DataLine /></el-icon>
          <div class="summary-content">
            <span class="label">总充电量</span>
            <span class="value">{{ totalCharge }} kWh</span>
          </div>
        </div>
      </div>
    </div>

    <div class="bill-content">
      <el-card class="bill-table">
        <el-table
            :data="dataSource"
            style="width: 100%"
            :stripe="true"
            :border="true"
            v-loading="loading"
        >
          <el-table-column prop="car_id" label="车辆编号" width="120" />
          <el-table-column prop="bill_id" label="账单ID" width="120" />
          <el-table-column prop="pile_id" label="充电桩ID" width="120" />
          <el-table-column prop="charge_amount" label="充电量(kWh)" width="120" />
          <el-table-column prop="charge_duration" label="充电时长" width="120" />
          <el-table-column prop="total_charge_fee" label="充电费用(元)" width="120" />
          <el-table-column prop="total_service_fee" label="服务费用(元)" width="120" />
          <el-table-column prop="total_fee" label="总费用(元)" width="120">
            <template #default="scope">
              <span class="total-fee">¥{{ scope.row.total_fee }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="start_time" label="启动时间" width="180" />
          <el-table-column prop="end_time" label="停止时间" width="180" />
          <el-table-column prop="detail_numbers" label="详单编号" width="180" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted, ref } from 'vue'
import axios from 'axios'
import { Money, Timer, DataLine } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  components: {
    Money,
    Timer,
    DataLine
  },
  setup() {
    const loading = ref(false)
    const totalAmount = ref(0)
    const totalDuration = ref('0分钟')
    const totalCharge = ref(0)

    // 用于存储表格数据
    const dataSource = reactive([])

    // 工具函数：将秒数转为"xx分钟xx秒"
    function formatDuration(seconds) {
      const min = Math.floor(seconds / 60)
      const sec = seconds % 60
      if (min > 0) {
        return `${min}分钟${sec}秒`
      } else {
        return `${sec}秒`
      }
    }

    // 计算总金额和总时长
    const calculateTotals = (bills) => {
      let amount = 0
      let duration = 0 // 单位：秒
      let charge = 0

      bills.forEach(bill => {
        amount += parseFloat(bill.total_fee) || 0
        charge += parseFloat(bill.charge_amount) || 0
        // 兼容bill.charge_duration为字符串或数字
        let d = bill.charge_duration
        if (typeof d === 'string') {
          // 解析"xx分钟xx秒"
          const match = d.match(/(\d+)分钟(\d+)秒/)
          if (match) {
            d = parseInt(match[1]) * 60 + parseInt(match[2])
          } else {
            d = parseInt(d)
          }
        }
        duration += d || 0
      })

      totalAmount.value = amount.toFixed(2)
      totalCharge.value = charge.toFixed(2)
      // 统一显示"xx分钟xx秒"
      const min = Math.floor(duration / 60)
      const sec = duration % 60
      totalDuration.value = `${min}分钟${sec}秒`
    }

    // 执行 HTTP 请求，获取数据
    const fetchData = async () => {
      loading.value = true
      try {
        const car_id = localStorage.getItem('car_id')
        if (!car_id) {
          ElMessage.error('未找到车辆信息，请先登录')
          return
        }
        const response = await axios.get(process.env.VUE_APP_BACKEND_URL + '/user/checkBill?car_id=' + car_id)
        const { data } = response.data
        // 格式化数据：账单ID和充电桩ID为字符串，充电时长单位为"xx分钟xx秒"
        const formattedData = data.bills.map(bill => ({
          ...bill,
          bill_id: Array.isArray(bill.bill_id) ? bill.bill_id.join(', ') : String(bill.bill_id ?? ''),
          pile_id: Array.isArray(bill.pile_id) ? bill.pile_id.join(', ') : String(bill.pile_id ?? ''),
          charge_duration: formatDuration(bill.charge_duration),
          start_time: new Date(bill.start_time).toLocaleString(),
          end_time: new Date(bill.end_time).toLocaleString()
        }))
        dataSource.length = 0
        dataSource.push(...formattedData)
        calculateTotals(formattedData)
      } catch (error) {
        console.error('Error fetching bill data:', error)
        ElMessage.error('获取账单数据失败')
      } finally {
        loading.value = false
      }
    }

    // 在组件挂载后执行一次 HTTP 请求
    onMounted(() => {
      console.log('Component mounted, checking sessionStorage...')
      console.log('All sessionStorage items:', Object.keys(sessionStorage))
      fetchData()
    })

    return {
      dataSource,
      loading,
      totalAmount,
      totalDuration,
      totalCharge
    }
  }
}
</script>

<style scoped>
.bill-container {
  padding: 24px;
  min-height: 100vh;
  background: #f5f7fa;
}

.bill-header {
  margin-bottom: 24px;
}

.bill-header h2 {
  color: #2b3391;
  margin-bottom: 24px;
  font-size: 24px;
}

.bill-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.summary-card {
  background: linear-gradient(135deg, #2b3391 0%, #3d47b3 100%);
  padding: 24px;
  border-radius: 12px;
  color: white;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.3s ease;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-card .el-icon {
  font-size: 32px;
}

.summary-content {
  display: flex;
  flex-direction: column;
}

.summary-content .label {
  font-size: 14px;
  opacity: 0.8;
}

.summary-content .value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 4px;
}

.bill-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(43, 51, 145, 0.1);
}

.bill-table {
  border: none;
  box-shadow: none;
}

.total-fee {
  color: #2b3391;
  font-weight: bold;
}

:deep(.el-table) {
  --el-table-border-color: #e4e7ed;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #2b3391;
  font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

@media (max-width: 768px) {
  .bill-container {
    padding: 16px;
  }

  .bill-summary {
    grid-template-columns: 1fr;
  }

  .summary-card {
    padding: 16px;
  }

  .summary-content .value {
    font-size: 20px;
  }
}
</style>
